/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    // Time: O(n); Space: O(1).
    void reorderList(ListNode* head) {
        if (!head || !head->next || !head->next->next) return;
        
        // 快慢指针找中点
        ListNode* slow = head, * fast = head;
        while (fast->next && fast->next->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode* dummy = new ListNode(-1);
        dummy->next = slow->next;
        slow->next = nullptr;

        // 翻转后半部分
        ListNode* prev = dummy;
        ListNode* curr = prev->next;
        ListNode* next;
        while (curr->next) {
            next = curr->next;
            curr->next = next->next;
            next->next = prev->next;
            prev->next = next;
        }

        // 合并两个链表
        ListNode* curr1 = head, * curr2 = dummy->next;
        ListNode* temp1, * temp2;
        while (curr1 && curr2) {
            temp1 = curr1->next;
            temp2 = curr2->next;
            curr1->next = curr2;
            curr2->next = temp1;
            curr1 = temp1;
            curr2 = temp2;
        }
    }
};
